import { Element } from 'cheerio'
import Head from 'next/head'
import { dataService } from '../services'
import { toRelativeTime, transformId } from '../utils'
import styles from '../styles/index.module.css'

function Group(
  { title, url, items }:
    { title: string, url: string, items: IListItem[] }
) {
  let hasItems = Array.isArray(items) && items.length > 0
  return (
    <div className={styles.group}>
      <div className={styles['group-header']}>
        <a className={styles['group-title']} href={url}>{title}</a>
      </div>
      <div className={styles['group-body']}>
        {
          hasItems && items.map((item) => (
            <a key={item.id} target="_blank" rel="noreferrer" href={`/detail/${item.id}`} title={item.title}>
              <div>
                <img className="cover" src={`/api/cover/${item.id}`} />
              </div>
              <span>{item.title}</span>
              <em title={item.date}>{item.relativeTime}</em>
            </a>
          ))
        }
      </div>
    </div >
  )
}


export default function Home({ news, zonghe, dongman, hytv, rihantv, zongyi }: IHomeModel) {
  return (
    <>
      <Head>
        <title>{process.env.siteName}</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <div className={styles.container}>
        <Group title="最新电影" url="/list/gndy/dyzz" items={news} />
        <Group title="经典电影" url="/list/gndy/jddy" items={zonghe} />
        <Group title="华语电视剧" url="/list/tv/hytv" items={hytv} />
        <Group title="日韩电视剧" url="/list/tv/rihantv" items={rihantv} />
        <Group title="最新综艺" url="/list/zongyi2013" items={zongyi} />
        <Group title="最新动漫" url="/list/dongman" items={dongman} />
        <script src="/js/cover.js"></script>
      </div>
    </>
  )
}

export async function getServerSideProps(props: any) {

  let $ = await dataService.getIndexDoc()

  let items1 = $('.co_area2 .co_content8')
  let items2 = $('.co_area2 .co_content3')

  function handleItems($ele: Element) {
    let data = [] as IListItem[]
    if ($ele) {
      $($ele).find('tr').each<any>(function () {
        let $tds = $(this).find('td')
        if ($tds.length == 2) {
          let dataItem = {} as IListItem
          let $title = $tds.first().find('a').last()
          dataItem.id = transformId($title.attr('href')?.replace('/html/', '')!)
          dataItem.title = $title.text()
          dataItem.date = $tds.last().text().trim()
          dataItem.relativeTime = toRelativeTime(dataItem.date)
          data.push(dataItem)
        }
      })
    }
    return data
  }

  let res: IHomeModel = {
    news: handleItems(items1.get(0)),
    zonghe: handleItems(items1.get(1)),
    dongman: handleItems(items1.get(2)),
    hytv: handleItems(items2.get(0)),
    rihantv: handleItems(items2.get(1)),
    zongyi: handleItems(items2.get(3)),
  }
  for (const key in res) {
    let len = (res as any)[key].length
    if (len > 10) {
      len = 10
    } else if (len > 5 && len < 10) {
      len = 5
    }
    (res as any)[key].length = len
  }

  return { props: res }
}


interface IHomeModel {
  news: IListItem[]
  zonghe: IListItem[]
  dongman: IListItem[]
  hytv: IListItem[]
  rihantv: IListItem[]
  zongyi: IListItem[]
}

interface IListItem {
  id: string
  title: string
  date: string
  relativeTime: string
}